package logic

import (
	"community/communityrpc/communityrpc"
	"community/communityrpc/internal/svc"
	"community/models/mysqlinit"
	"community/models/redisinit"
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListPostsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPostsLogic {
	return &ListPostsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListPostsLogic) ListPosts(in *communityrpc.ListPostsRequest) (*communityrpc.ListPostsResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var count int64
	var pro []mysqlinit.Post
	query := mysqlinit.DB.Debug().Model(&mysqlinit.Post{})

	query.Count(&count)
	get := redisinit.Client.Get("like" + strconv.FormatInt(offset, 10))
	if get.Val() == "" {
		query.Order("created_at desc").Offset(int(offset)).Limit(int(pageSize)).Find(&pro)
		marshal, _ := json.Marshal(&pro)
		fmt.Println(marshal)
		redisinit.Client.Set("like"+strconv.FormatInt(offset, 10), marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &pro)
	}
	var commun []*communityrpc.PostList
	for _, i := range pro {
		list := communityrpc.PostList{
			CreatedAt: i.CreatedAt.Format(time.DateTime),
			UserId:    i.UserId,
			Image:     i.Image,
			Content:   i.Content,
		}
		commun = append(commun, &list)
	}
	return &communityrpc.ListPostsResponse{
		List:  commun,
		Count: count,
	}, nil
}
